package db

import (
	"fmt"
	"strings"

	"git.sr.ht/~mil/mobroute/src/utilfuncs"
)

// LoadStopWalks loads stopwalks given the input origin coordinate and a max
// distance in km to walk
func (c *DBConnection) LoadStopWalks(originPoint utilfuncs.Coord, maxWalkKM float64) (*[]StopWalk, error) {
	var (
		r     []StopWalk
		query = fmt.Sprintf(
			`
				with input_coord as (select ? as lat, ? as lon)
				select
					distinct vsp.source || '_' || vsp.parent_station as stop_sidu,
					s.stop_name,
					iif(
						ext_haversinedistkm(s.stop_lat, s.stop_lon, input_coord.lat, input_coord.lon) > ?,
						null,
						ext_haversinedistkm(s.stop_lat, s.stop_lon, input_coord.lat, input_coord.lon)
					) as dist_km
				from
				  input_coord
				  join stops s on s.source in (%s)
				  join _cvstopparent vsp on vsp.parent_station = s.stop_id
				  order by dist_km asc
			`,
			strings.Join(utilfuncs.ArrayWithValue(len(c.QuerySources), "?"), ","),
		)
		params = append(
			[]any{originPoint.Lat, originPoint.Lon, maxWalkKM},
			utilfuncs.Anyify(utilfuncs.ArrayIntToArryString(c.QuerySources))...,
		)
	)

	if err := queryToSlice(c, query, params, &r); err != nil {
		return nil, err
	} else {
		return &r, nil
	}
}
